package com.example.intenttrial.bezier;

import java.util.ArrayList;
import java.util.List;

public class BezierHelper {
	private List<Point> curvePoints;
	private List<Point> supportVertexies;
	private int n;

	public void init(List<Point> points) {
		curvePoints = new ArrayList<Point>();
		supportVertexies = points;
		n = supportVertexies.size() - 1;
	}
	
	public List<Point> process(float delta) {
		curvePoints.clear();
		float t = 0f;
		while(t <= 1) {
			
			Point pointToAdd = bt(t);
			curvePoints.add(pointToAdd);
			
			t += delta;
		}
		return curvePoints;
	}
	
	public List<Point> getSupportVertexies() {
		return supportVertexies;
	}
	
	private Point bt(float t) {
		Point point = new Point();
		
		for(int i = 0; i <= n; i++) {
			Point p = Point.multiplyByValue(supportVertexies.get(i), bi(i, n, t));
			point = Point.add(point, p);
		}
		
		return point;
	}
	
	private float bi(int i, int n, float t) {
		float a = (float) (Math.pow(t, i) * Math.pow((1 -t), (n -i)));
		float b = polinomialCoeficient(i, n); 
		return a * b;
	}
	
	private float polinomialCoeficient(int k, int n) {
		float result = factorial(n) / (factorial(k) * factorial(n - k));
		return result;
	}
	
	private int factorial(int n) {
		if(n != 0) {
			return n * factorial(n - 1);
		} 
		return 1;
	}
	
}
